package com.lunm.im.client;

import com.lunm.im.factory.HandlerFactory;
import com.lunm.im.massage.RpcRequestMessage;
import com.lunm.im.protocol.IMLengthFieldBasedFrameDecoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;


/**
 * @version 1.0.0
 * @Author shawn
 * @Date 2024/12/31 8:55
 */
@Slf4j
public class RpcClient {
    public static void main(String[] args) {
        NioEventLoopGroup group = new NioEventLoopGroup();

        try {
            Channel channel = new Bootstrap()
                    .group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new IMLengthFieldBasedFrameDecoder());
                            ch.pipeline().addLast(HandlerFactory.getLoggingHandler());
                            ch.pipeline().addLast(HandlerFactory.getMessageCodec());
                            ch.pipeline().addLast(HandlerFactory.getRpcResponseHandler());
                        }
                    })
                    .connect("localhost", 8080).sync().channel();
            channel.writeAndFlush(new RpcRequestMessage(1, "com.lunm.im.server.service.HelloService", "sayHello", String.class, new Class[]{String.class}, new Object[]{"张三"}));
            channel.closeFuture().sync();
        } catch (InterruptedException e) {
            log.error("server error", e);
        } finally {
            group.shutdownGracefully();
        }
    }
}
